let storageKeys = require('../include/storage-keys')
let storage = require('../include/xstorage')
let broadcastChannelKeys = require('../include/broadcast-channel-keys')
let BroadcastChannel = require('./broadcast-channel')
let bc = new BroadcastChannel(broadcastChannelKeys.ITEM_SELECTION_CART)
let modal = weex.requireModule('modal')
let Cart = {
  userItemSelectList: [],
  initUserItemSelection () {
    return storage.getItem(storageKeys.USER_ITEM_SELECTION).done(rs => {
      this.userItemSelectList = rs || []
    })
  },
  selectItemToSelection (item, flag) {
    if (this.userItemSelectList.length === 9 && flag) {
      modal.alert({message: '选品车最多添加9个商品，请先保存后才可以继续添加！'})
      return false
    }
    for (var i in this.userItemSelectList) {
      if (item.id && item.id === this.userItemSelectList[i].id) {
        if (!flag) {
          this.userItemSelectList.splice(i, 1)
        }
      } else if (item.sourceItemId &&
          item.sourceItemId === this.userItemSelectList[i].sourceItemId &&
          item.ecomPlat === this.userItemSelectList[i].ecomPlat) {
        if (!flag) {
          this.userItemSelectList.splice(i, 1)
        }
      }
    }
    if (flag) {
      this.userItemSelectList.push(item)
    }
    storage.setItem(storageKeys.USER_ITEM_SELECTION, this.userItemSelectList)
    return true
  },
  checkItemSelected (item) {
    for (var i in this.userItemSelectList) {
      if ((item.id && item.id === this.userItemSelectList[i].id) || (item.sourceItemId &&
        item.sourceItemId === this.userItemSelectList[i].sourceItemId &&
        item.ecomPlat === this.userItemSelectList[i].ecomPlat)) {
        return true
      }
    }
    return false
  },
  clear () {
    bc.postMessage({
      action: 'clear'
    })
  },
  del (item) {
    bc.postMessage({
      action: 'del',
      item: item
    })
  },
  change (fn) {
    this.changeCallback = fn
  },
  triggerChange () {
    this.changeCallback && this.changeCallback()
  }
}
new BroadcastChannel(broadcastChannelKeys.ITEM_SELECTION_CART).onmessage = (e) => {
  if (e.data) {
    let data = e.data
    switch (data.action) {
      case 'clear':
        Cart.userItemSelectList = []
        storage.setItem(storageKeys.USER_ITEM_SELECTION, Cart.userItemSelectList)
        break
      case 'del':
        Cart.selectItemToSelection(data.item, false)
        break
    }
    Cart.triggerChange()
  }
}
module.exports = Cart
